import { LogHelper } from "../../utils/logHelper";

export class RoadTask implements IFlagTask{
  run(flag: Flag): void {
    let planningRoom:Room|undefined = undefined; // 需要规划的房间
    let targetRoom:Room|undefined = undefined; // 目标的房间（可以与规划的房间相同）

    // 判断是否外矿房间 
    const managerFlag = Game.flags[`外矿房间管理:${flag.pos.roomName}`]
    if(managerFlag){
      // 外矿房间
      planningRoom = flag.room;
      targetRoom = Game.rooms[managerFlag.memory.outerOre.closestRoom];
    }
    else {
      planningRoom = flag.room;
      targetRoom = flag.room;
    }

    if(targetRoom && planningRoom){
      let planningPath:Array<PathStep[]> = new Array<PathStep[]>;
      // 规划控制器的道路
      const spawn = targetRoom.spawn();
      const controller = planningRoom.controller;
      
      if(spawn && controller){
        const path = controller.pos.findPathTo(spawn);
        planningPath.push(path);
      }
      // 规划资源采集的道路
      const sources = planningRoom.find(FIND_SOURCES);
      for(const source of sources){
        if(spawn){
          const path = source.pos.findPathTo(spawn);
          planningPath.push(path);
        }
      }
      // 放置道路工地
      if(planningPath.length > 0){
        for(const path of planningPath){
          for(const pos of path){
            planningRoom.createConstructionSite(pos.x,pos.y,STRUCTURE_ROAD);
          }
        }
      }
      LogHelper.log(`Flag[${flag.name}] 房间 ${flag.pos.roomName} 规划完成`);
    }
    else {
      LogHelper.error(`Flag[${flag.name}] 房间 ${flag.pos.roomName} 规划房间或目标房间错误`);
    }
    flag.remove();
  }
}